<template>
  <view class="page-container">
    <!-- 批量排班表单 -->
    <scroll-view class="content-area" :scroll-y="true" :style="{ height: scrollHeight }">
      <view class="form-container">
      <!-- 排班设置 -->
      <view class="form-section">
        <view class="section-title">排班设置</view>
        
        <!-- 排班周期 -->
        <view class="form-item">
          <text class="form-label">排班周期 *</text>
          <u-radio-group v-model="batchData.cycleType" @change="handleCycleChange">
            <u-radio 
              v-for="cycle in cycleOptions" 
              :key="cycle.value"
              :name="cycle.value"
              :label="cycle.label"
            ></u-radio>
          </u-radio-group>
        </view>

        <!-- 开始日期 -->
        <view class="form-item">
          <text class="form-label">开始日期 *</text>
          <u-datetime-picker
            v-model="batchData.startDate"
            mode="date"
            :min-date="minDate"
            :max-date="maxDate"
            @change="handleStartDateChange"
          >
            <view class="picker-display">
              <text class="picker-text">{{ formatDate(batchData.startDate) }}</text>
              <u-icon name="calendar" color="#999" size="16"></u-icon>
            </view>
          </u-datetime-picker>
        </view>

        <!-- 结束日期 -->
        <view class="form-item">
          <text class="form-label">结束日期 *</text>
          <u-datetime-picker
            v-model="batchData.endDate"
            mode="date"
            :min-date="batchData.startDate"
            :max-date="maxDate"
            @change="handleEndDateChange"
          >
            <view class="picker-display">
              <text class="picker-text">{{ formatDate(batchData.endDate) }}</text>
              <u-icon name="calendar" color="#999" size="16"></u-icon>
            </view>
          </u-datetime-picker>
        </view>

        <!-- 工作区域 -->
        <view class="form-item">
          <text class="form-label">工作区域</text>
          <u-button 
            type="primary" 
            text="选择区域" 
            plain
            @click="selectWorkArea"
          ></u-button>
          <view v-if="selectedWorkArea" class="area-info">
            <text class="area-name">{{ selectedWorkArea.displayName }}</text>
            <u-icon 
              name="close" 
              size="16" 
              color="#999"
              @click="clearWorkArea"
            ></u-icon>
          </view>
        </view>
      </view>

      <!-- 人员选择 -->
      <view class="form-section">
        <view class="section-title">人员选择</view>
        
        <!-- 选择方式 -->
        <view class="form-item">
          <text class="form-label">选择方式 *</text>
          <u-radio-group v-model="batchData.selectType" @change="handleSelectTypeChange">
            <u-radio 
              v-for="type in selectTypeOptions" 
              :key="type.value"
              :name="type.value"
              :label="type.label"
            ></u-radio>
          </u-radio-group>
        </view>


        <!-- 按角色选择 -->
        <view v-if="batchData.selectType === 'role'" class="form-item">
          <text class="form-label">选择角色 *</text>
          <u-button 
            type="primary" 
            text="选择角色" 
            plain
            :disabled="!batchData.propertyCompanyId"
            @click="selectRole"
          ></u-button>
          <view v-if="!batchData.propertyCompanyId" class="disabled-tip">
            <text class="tip-text">请先选择工作区域 (propertyCompanyId: {{ batchData.propertyCompanyId }})</text>
          </view>
          <view v-if="selectedRole" class="role-info">
            <text class="role-name">{{ selectedRole.name }}</text>
            <text class="staff-count">({{ selectedRole.staffCount }}人)</text>
            <u-icon 
              name="close" 
              size="16" 
              color="#999"
              @click="clearRole"
            ></u-icon>
          </view>
        </view>

        <!-- 手动选择人员 -->
        <view v-if="batchData.selectType === 'manual'" class="form-item">
          <text class="form-label">选择人员 *</text>
          <u-button 
            type="primary" 
            text="选择人员" 
            plain
            :disabled="!batchData.propertyCompanyId"
            @click="selectStaff"
          ></u-button>
          <view v-if="!batchData.propertyCompanyId" class="disabled-tip">
            <text class="tip-text">请先选择工作区域 (propertyCompanyId: {{ batchData.propertyCompanyId }})</text>
          </view>
          <view v-if="selectedStaff.length > 0" class="selected-staff">
            <view 
              v-for="staff in selectedStaff" 
              :key="staff.id"
              class="staff-tag"
            >
              <text class="staff-name">{{ staff.name }}</text>
              <u-icon 
                name="close" 
                size="16" 
                color="#fff"
                @click="removeStaff(staff.id)"
              ></u-icon>
            </view>
          </view>
        </view>
      </view>

      <!-- 班次设置 -->
      <view class="form-section">
        <view class="section-title">班次设置</view>
        
        <!-- 排班模式 -->
        <view class="form-item">
          <text class="form-label">排班模式 *</text>
          <u-radio-group v-model="batchData.scheduleMode" @change="handleScheduleModeChange">
            <u-radio 
              v-for="mode in scheduleModeOptions" 
              :key="mode.value"
              :name="mode.value"
              :label="mode.label"
            ></u-radio>
          </u-radio-group>
        </view>

        <!-- 班次模板 -->
        <view v-if="batchData.scheduleMode === 'template'" class="form-item">
          <text class="form-label">班次模板 *</text>
          <u-button 
            type="info" 
            text="选择模板" 
            plain
            @click="selectTemplate"
          ></u-button>
          <view v-if="selectedTemplate" class="template-info">
            <text class="template-name">{{ selectedTemplate.name }}</text>
            <u-icon 
              name="close" 
              size="16" 
              color="#999"
              @click="clearTemplate"
            ></u-icon>
          </view>
        </view>

        <!-- 自定义班次 -->
        <view v-if="batchData.scheduleMode === 'custom'" class="form-item">
          <text class="form-label">自定义班次 *</text>
          <u-button 
            type="success" 
            text="添加班次" 
            icon="plus"
            @click="addShift"
          ></u-button>
        </view>

        <!-- 班次列表 -->
        <view v-if="batchData.shifts.length > 0" class="shifts-list">
          <view 
            v-for="(shift, index) in batchData.shifts" 
            :key="index"
            class="shift-item"
          >
            <view class="shift-info">
              <text class="shift-name">{{ shift.name }}</text>
              <text class="shift-time">{{ shift.startTime }} - {{ shift.endTime }}</text>
            </view>
            <view class="shift-actions">
              <u-button 
                type="text" 
                text="编辑" 
                size="mini"
                @click="editShift(index)"
              ></u-button>
              <u-button 
                type="text" 
                text="删除" 
                size="mini"
                color="#ff4757"
                @click="removeShift(index)"
              ></u-button>
            </view>
          </view>
        </view>
      </view>

      <!-- 排班规则 -->
      <view class="form-section">
        <view class="section-title">排班规则</view>
        
        <!-- 排班备注 -->
        <view class="form-item">
          <text class="form-label">排班备注</text>
          <u-textarea
            v-model="batchData.remark"
            placeholder="请输入批量排班备注信息"
            :maxlength="200"
            :count="true"
          ></u-textarea>
        </view>

        <!-- 排班预览 -->
        <view class="form-item">
          <text class="form-label">排班预览</text>
          <u-button 
            type="warning" 
            text="预览排班" 
            icon="eye"
            @click="previewSchedule"
          ></u-button>
        </view>
      </view>
      </view>
    </scroll-view>

    <!-- 底部操作按钮 -->
    <view class="bottom-actions">
      <u-button 
        type="default" 
        text="取消" 
        @click="() => uni.navigateBack()"
      ></u-button>
      <u-button 
        type="primary" 
        text="保存并发布" 
        @click="saveAndPublish"
      ></u-button>
    </view>

    <!-- 班次编辑弹窗 -->
    <view v-if="showShiftEdit" class="popup-overlay" @click="closeShiftEdit">
      <view class="shift-edit-popup" @click.stop>
        <view class="popup-header">
          <text class="popup-title">{{ editingShiftIndex >= 0 ? '编辑班次' : '添加班次' }}</text>
          <u-icon 
            name="close" 
            size="20" 
            color="#999"
            @click="closeShiftEdit"
          ></u-icon>
        </view>
        
        <view class="popup-content">
          <view class="form-item">
            <text class="form-label">班次名称 *</text>
            <u-input
              v-model="shiftForm.name"
              placeholder="请输入班次名称"
            ></u-input>
          </view>
          
          <view class="form-item">
            <text class="form-label">开始时间 *</text>
            <u-datetime-picker
              v-model="shiftForm.startTime"
              mode="time"
              @change="handleStartTimeChange"
            >
              <view class="picker-display">
                <text class="picker-text">{{ shiftForm.startTime }}</text>
                <u-icon name="clock" color="#999" size="16"></u-icon>
              </view>
            </u-datetime-picker>
          </view>
          
          <view class="form-item">
            <text class="form-label">结束时间 *</text>
            <u-datetime-picker
              v-model="shiftForm.endTime"
              mode="time"
              @change="handleEndTimeChange"
            >
              <view class="picker-display">
                <text class="picker-text">{{ shiftForm.endTime }}</text>
                <u-icon name="clock" color="#999" size="16"></u-icon>
              </view>
            </u-datetime-picker>
          </view>
        </view>
        
        <view class="popup-actions">
          <u-button 
            type="default" 
            text="取消" 
            @click="closeShiftEdit"
          ></u-button>
          <u-button 
            type="primary" 
            text="确定" 
            @click="saveShift"
          ></u-button>
        </view>
      </view>
    </view>

    <!-- 排班预览弹窗 -->
    <view v-if="showPreview" class="popup-overlay" @click="closePreview">
      <view class="preview-popup" @click.stop>
        <view class="popup-header">
          <text class="popup-title">排班预览</text>
          <u-icon 
            name="close" 
            size="20" 
            color="#999"
            @click="closePreview"
          ></u-icon>
        </view>
        
        <view class="popup-content">
          <view class="preview-info">
            <text class="preview-text">排班周期：{{ formatDate(batchData.startDate) }} - {{ formatDate(batchData.endDate) }}</text>
            <text class="preview-text">排班人员：{{ getSelectedStaffCount() }}人</text>
            <text class="preview-text">班次设置：{{ batchData.shifts.length }}个班次</text>
          </view>
          
          <view class="preview-schedule">
            <text class="preview-title">排班安排预览：</text>
            <view class="schedule-preview-list">
              <view 
                v-for="(day, index) in previewDays" 
                :key="index"
                class="preview-day"
              >
                <text class="day-date">{{ day.date }}</text>
                <text class="day-shift">{{ day.shift }}</text>
              </view>
            </view>
          </view>
        </view>
        
        <view class="popup-actions">
          <u-button 
            type="default" 
            text="关闭" 
            @click="closePreview"
          ></u-button>
          <u-button 
            type="primary" 
            text="确认排班" 
            @click="confirmSchedule"
          ></u-button>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
/**
 * 批量排班页面
 * @author Wu.Liang
 * @date 2025-01-30
 * @version 1.0.0
 */

import { ref, reactive, computed, onMounted, onUnmounted } from 'vue'
import { regionApi } from '@/api/region'
import { staffApi, roleApi } from '@/api/staff'

// 页面高度计算
const scrollHeight = ref('calc(100vh - 120px)')

// 响应式数据
const batchData = reactive({
  cycleType: 'week', // week: 按周, month: 按月
  startDate: new Date(),
  endDate: new Date(),
  workAreaId: null,
  propertyCompanyId: null, // 物业公司ID，从选择的区域中获取
  selectType: 'role', // role: 按角色, manual: 手动选择
  roleId: null,
  staffIds: [],
  scheduleMode: 'template', // template: 模板, custom: 自定义
  templateId: null,
  shifts: [],
  remark: ''
})

const selectedWorkArea = ref(null)
const selectedRole = ref(null)
const selectedStaff = ref([])
const selectedTemplate = ref(null)
const showShiftEdit = ref(false)
const showPreview = ref(false)
const editingShiftIndex = ref(-1)

const shiftForm = reactive({
  name: '',
  startTime: '08:00',
  endTime: '16:00'
})

const minDate = ref(new Date())
const maxDate = ref(new Date(2025, 11, 31))

// 选项数据
const cycleOptions = ref([
  { value: 'week', label: '按周排班' },
  { value: 'month', label: '按月排班' }
])

const selectTypeOptions = ref([
  { value: 'role', label: '按角色选择' },
  { value: 'manual', label: '手动选择' }
])

const scheduleModeOptions = ref([
  { value: 'template', label: '使用模板' },
  { value: 'custom', label: '自定义班次' }
])


// 角色数据
const roles = ref([])
const loadingRoles = ref(false)

// 工作区域数据
const workAreas = ref([])
const loadingWorkAreas = ref(false)

// 人员数据
const staffList = ref([])
const loadingStaff = ref(false)

// 班次模板数据
const shiftTemplates = ref([
  {
    id: 1,
    name: '标准早班',
    shifts: [
      { name: '早班', startTime: '08:00', endTime: '16:00' }
    ]
  },
  {
    id: 2,
    name: '标准晚班',
    shifts: [
      { name: '晚班', startTime: '16:00', endTime: '24:00' }
    ]
  },
  {
    id: 3,
    name: '三班倒',
    shifts: [
      { name: '早班', startTime: '08:00', endTime: '16:00' },
      { name: '中班', startTime: '16:00', endTime: '24:00' },
      { name: '夜班', startTime: '00:00', endTime: '08:00' }
    ]
  }
])

// 预览数据
const previewDays = ref([])

// 计算属性
const getSelectedStaffCount = () => {
  if (batchData.selectType === 'role' && selectedRole.value) {
    return selectedRole.value.staffCount
  } else if (batchData.selectType === 'manual') {
    return selectedStaff.value.length
  }
  return 0
}

// 方法

const saveBatchSchedule = () => {
  if (!validateForm()) {
    return
  }
  
  uni.showLoading({ title: '保存中...' })
  
  // 模拟保存请求
  setTimeout(() => {
    uni.hideLoading()
    uni.showToast({
      title: '批量排班保存成功',
      icon: 'success'
    })
    setTimeout(() => {
      uni.navigateBack()
    }, 1500)
  }, 1000)
}

const saveAndPublish = () => {
  if (!validateForm()) {
    return
  }
  
  uni.showLoading({ title: '发布中...' })
  
  // 模拟发布请求
  setTimeout(() => {
    uni.hideLoading()
    uni.showToast({
      title: '批量排班发布成功',
      icon: 'success'
    })
    setTimeout(() => {
      uni.navigateBack()
    }, 1500)
  }, 1000)
}

const validateForm = () => {
  if (batchData.selectType === 'role' && !selectedRole.value) {
    uni.showToast({
      title: '请选择角色',
      icon: 'none'
    })
    return false
  }
  
  if (batchData.selectType === 'manual' && selectedStaff.value.length === 0) {
    uni.showToast({
      title: '请选择人员',
      icon: 'none'
    })
    return false
  }
  
  if (batchData.shifts.length === 0) {
    uni.showToast({
      title: '请设置班次信息',
      icon: 'none'
    })
    return false
  }
  
  return true
}

const handleCycleChange = (value) => {
  batchData.cycleType = value
  if (value === 'week') {
    // 按周排班，结束日期设为开始日期后7天
    batchData.endDate = new Date(batchData.startDate.getTime() + 7 * 24 * 60 * 60 * 1000)
  } else if (value === 'month') {
    // 按月排班，结束日期设为开始日期后30天
    batchData.endDate = new Date(batchData.startDate.getTime() + 30 * 24 * 60 * 60 * 1000)
  }
}

const handleStartDateChange = (date) => {
  batchData.startDate = date
  if (batchData.cycleType === 'week') {
    batchData.endDate = new Date(date.getTime() + 7 * 24 * 60 * 60 * 1000)
  } else if (batchData.cycleType === 'month') {
    batchData.endDate = new Date(date.getTime() + 30 * 24 * 60 * 60 * 1000)
  }
}

const handleEndDateChange = (date) => {
  batchData.endDate = date
}

const handleSelectTypeChange = (value) => {
  batchData.selectType = value
  // 清空之前的选择
  selectedRole.value = null
  selectedStaff.value = []
}

const handleScheduleModeChange = (value) => {
  batchData.scheduleMode = value
  if (value === 'template') {
    batchData.shifts = []
  }
}

const selectWorkArea = () => {
  if (workAreas.value.length === 0) {
    loadWorkAreas()
    return
  }
  
  uni.showActionSheet({
    itemList: workAreas.value.map(area => area.displayName),
    success: (res) => {
      selectedWorkArea.value = workAreas.value[res.tapIndex]
      batchData.workAreaId = selectedWorkArea.value.zoneId
      // 记录物业公司ID
      batchData.propertyCompanyId = selectedWorkArea.value.propertyCompanyId
      
      // 清空之前的人员选择
      selectedRole.value = null
      selectedStaff.value = []
      batchData.roleId = null
      batchData.staffIds = []
      
      console.log('选择工作区域成功，物业公司ID：', batchData.propertyCompanyId)
      console.log('选择的工作区域数据：', selectedWorkArea.value)
    }
  })
}

const clearWorkArea = () => {
  selectedWorkArea.value = null
  batchData.workAreaId = null
  batchData.propertyCompanyId = null
  
  // 清空人员选择
  selectedRole.value = null
  selectedStaff.value = []
  batchData.roleId = null
  batchData.staffIds = []
  
  console.log('清空工作区域，物业公司ID已清空')
}

// 加载工作区域列表
const loadWorkAreas = async () => {
  if (loadingWorkAreas.value) {
    return
  }
  
  loadingWorkAreas.value = true
  uni.showLoading({ title: '加载中...' })
  
  try {
    // 使用统一的API服务层调用
    const response = await regionApi.getWorkAreas()
    
    if (response && response.code === 200) {
      workAreas.value = response.data || []
      uni.hideLoading()
      
      // 重新显示选择器
      uni.showActionSheet({
        itemList: workAreas.value.map(area => area.displayName),
        success: (res) => {
          selectedWorkArea.value = workAreas.value[res.tapIndex]
          batchData.workAreaId = selectedWorkArea.value.zoneId
          // 记录物业公司ID
          batchData.propertyCompanyId = selectedWorkArea.value.propertyCompanyId
          
          // 清空之前的人员选择
          selectedRole.value = null
          selectedStaff.value = []
          batchData.roleId = null
          batchData.staffIds = []
          
          console.log('选择工作区域成功，物业公司ID：', batchData.propertyCompanyId)
          console.log('选择的工作区域数据：', selectedWorkArea.value)
        }
      })
    } else {
      // 错误消息处理规范：后端返回的message字段 > 后端返回的msg字段 > 前端自定义消息
      const errorMessage = response?.message || response?.msg || '加载工作区域失败'
      throw new Error(errorMessage)
    }
  } catch (error) {
    console.error('加载工作区域失败:', error)
    uni.hideLoading()
    uni.showToast({
      title: error.message || '加载工作区域失败',
      icon: 'none'
    })
  } finally {
    loadingWorkAreas.value = false
  }
}


const selectRole = () => {
  if (!batchData.propertyCompanyId) {
    uni.showToast({
      title: '请先选择工作区域',
      icon: 'none'
    })
    return
  }
  
  if (roles.value.length === 0) {
    loadRoles()
    return
  }
  
  uni.showActionSheet({
    itemList: roles.value.map(role => `${role.roleName} (${role.userCount || 0}人)`),
    success: (res) => {
      selectedRole.value = roles.value[res.tapIndex]
      batchData.roleId = selectedRole.value.id
    }
  })
}

const clearRole = () => {
  selectedRole.value = null
  batchData.roleId = null
}

// 加载角色列表
const loadRoles = async () => {
  if (loadingRoles.value || !batchData.propertyCompanyId) {
    return
  }
  
  loadingRoles.value = true
  uni.showLoading({ title: '加载中...' })
  
  try {
    // 根据物业公司ID获取角色列表
    const response = await roleApi.getRolesByPropertyCompany(batchData.propertyCompanyId)
    
    if (response && response.code === 200) {
      roles.value = response.data || []
      uni.hideLoading()
      
      // 重新显示选择器
      uni.showActionSheet({
        itemList: roles.value.map(role => `${role.roleName} (${role.userCount || 0}人)`),
        success: (res) => {
          selectedRole.value = roles.value[res.tapIndex]
          batchData.roleId = selectedRole.value.id
        }
      })
    } else {
      // 错误消息处理规范：后端返回的message字段 > 后端返回的msg字段 > 前端自定义消息
      const errorMessage = response?.message || response?.msg || '加载角色列表失败'
      throw new Error(errorMessage)
    }
  } catch (error) {
    console.error('加载角色列表失败:', error)
    uni.hideLoading()
    uni.showToast({
      title: error.message || '加载角色列表失败',
      icon: 'none'
    })
  } finally {
    loadingRoles.value = false
  }
}

const selectStaff = () => {
  if (!batchData.propertyCompanyId) {
    uni.showToast({
      title: '请先选择工作区域',
      icon: 'none'
    })
    return
  }
  
  // 跳转到按角色分组的用户选择页面
  uni.navigateTo({
    url: `/pages/property-work/staff-select-by-role?propertyCompanyId=${batchData.propertyCompanyId}`
  })
}

// 显示人员选择器
const showStaffSelector = () => {
  const staffNames = staffList.value.map(staff => staff.username || staff.nickname || staff.realName)
  
  uni.showActionSheet({
    itemList: staffNames,
    success: (res) => {
      const selectedStaffItem = staffList.value[res.tapIndex]
      if (selectedStaffItem) {
        // 检查是否已经选择过该人员
        const exists = selectedStaff.value.find(staff => staff.id === selectedStaffItem.id)
        if (exists) {
          uni.showToast({
            title: '该人员已选择',
            icon: 'none'
          })
          return
        }
        
        selectedStaff.value.push(selectedStaffItem)
        batchData.staffIds.push(selectedStaffItem.id)
      }
    }
  })
}

// 加载人员列表
const loadStaff = async () => {
  if (loadingStaff.value || !batchData.propertyCompanyId) {
    return
  }
  
  loadingStaff.value = true
  uni.showLoading({ title: '加载中...' })
  
  try {
    // 根据物业公司ID获取人员列表
    const response = await staffApi.getStaffByPropertyCompany(batchData.propertyCompanyId)
    
    if (response && response.code === 200) {
      staffList.value = response.data || []
      uni.hideLoading()
      
      // 显示人员选择器
      showStaffSelector()
    } else {
      // 错误消息处理规范：后端返回的message字段 > 后端返回的msg字段 > 前端自定义消息
      const errorMessage = response?.message || response?.msg || '加载人员列表失败'
      throw new Error(errorMessage)
    }
  } catch (error) {
    console.error('加载人员列表失败:', error)
    uni.hideLoading()
    uni.showToast({
      title: error.message || '加载人员列表失败',
      icon: 'none'
    })
  } finally {
    loadingStaff.value = false
  }
}

const removeStaff = (staffId) => {
  const index = selectedStaff.value.findIndex(staff => staff.id === staffId)
  if (index > -1) {
    selectedStaff.value.splice(index, 1)
    // 同时从batchData.staffIds中移除
    const staffIdIndex = batchData.staffIds.findIndex(id => id === staffId)
    if (staffIdIndex > -1) {
      batchData.staffIds.splice(staffIdIndex, 1)
    }
  }
}

const selectTemplate = () => {
  uni.showActionSheet({
    itemList: shiftTemplates.value.map(template => template.name),
    success: (res) => {
      const template = shiftTemplates.value[res.tapIndex]
      selectedTemplate.value = template
      batchData.templateId = template.id
      batchData.shifts = [...template.shifts]
    }
  })
}

const clearTemplate = () => {
  selectedTemplate.value = null
  batchData.templateId = null
  batchData.shifts = []
}

const addShift = () => {
  editingShiftIndex.value = -1
  shiftForm.name = ''
  shiftForm.startTime = '08:00'
  shiftForm.endTime = '16:00'
  showShiftEdit.value = true
}

const editShift = (index) => {
  editingShiftIndex.value = index
  const shift = batchData.shifts[index]
  shiftForm.name = shift.name
  shiftForm.startTime = shift.startTime
  shiftForm.endTime = shift.endTime
  showShiftEdit.value = true
}

const removeShift = (index) => {
  uni.showModal({
    title: '确认删除',
    content: '确定要删除这个班次吗？',
    success: (res) => {
      if (res.confirm) {
        batchData.shifts.splice(index, 1)
      }
    }
  })
}

const closeShiftEdit = () => {
  showShiftEdit.value = false
  editingShiftIndex.value = -1
}

const handleStartTimeChange = (time) => {
  shiftForm.startTime = time
}

const handleEndTimeChange = (time) => {
  shiftForm.endTime = time
}

const saveShift = () => {
  if (!shiftForm.name.trim()) {
    uni.showToast({
      title: '请输入班次名称',
      icon: 'none'
    })
    return
  }
  
  if (shiftForm.startTime >= shiftForm.endTime) {
    uni.showToast({
      title: '结束时间必须晚于开始时间',
      icon: 'none'
    })
    return
  }
  
  const shift = {
    name: shiftForm.name,
    startTime: shiftForm.startTime,
    endTime: shiftForm.endTime
  }
  
  if (editingShiftIndex.value >= 0) {
    batchData.shifts[editingShiftIndex.value] = shift
  } else {
    batchData.shifts.push(shift)
  }
  
  closeShiftEdit()
}

const previewSchedule = () => {
  if (!validateForm()) {
    return
  }
  
  // 生成预览数据
  generatePreviewData()
  showPreview.value = true
}

const generatePreviewData = () => {
  previewDays.value = []
  const startDate = new Date(batchData.startDate)
  const endDate = new Date(batchData.endDate)
  
  for (let d = new Date(startDate); d <= endDate; d.setDate(d.getDate() + 1)) {
    const dayOfWeek = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'][d.getDay()]
    const shift = batchData.shifts[0] || { name: '未设置', startTime: '', endTime: '' }
    
    previewDays.value.push({
      date: `${formatDate(d)} (${dayOfWeek})`,
      shift: `${shift.name} ${shift.startTime}-${shift.endTime}`
    })
  }
}

const closePreview = () => {
  showPreview.value = false
}

const confirmSchedule = () => {
  closePreview()
  saveAndPublish()
}

const formatDate = (date) => {
  const d = new Date(date)
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
}

// 处理用户选择结果
const onStaffSelected = (selectedUsers) => {
  console.log('收到选中的用户：', selectedUsers)
  
  // 更新选中的用户列表
  selectedStaff.value = selectedUsers
  batchData.staffIds = selectedUsers.map(user => user.id)
  
  uni.showToast({
    title: `已选择 ${selectedUsers.length} 人`,
    icon: 'success'
  })
}

onMounted(() => {
  // 页面加载时初始化数据
  batchData.endDate = new Date(batchData.startDate.getTime() + 7 * 24 * 60 * 60 * 1000)
  
  // 注册全局方法，供子页面调用
  uni.$on('staffSelected', onStaffSelected)
})

onUnmounted(() => {
  // 页面卸载时移除事件监听
  uni.$off('staffSelected', onStaffSelected)
})
</script>

<style scoped>
/* 页面容器规范 */
.page-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 16px;
}

/* 内容区域规范 */
.content-area {
  height: 100%;
  overflow-y: auto;
}

.form-container {
  padding: 30rpx;
}

.form-section {
  background-color: #fff;
  border-radius: 20rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 30rpx;
}

.form-item {
  margin-bottom: 30rpx;
}

.form-label {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
  display: block;
  margin-bottom: 20rpx;
}

.picker-display {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx;
  background-color: #f8f9fa;
  border-radius: 12rpx;
  border: 1rpx solid #eee;
}

.picker-text {
  font-size: 28rpx;
  color: #333;
}

.area-info,
.role-info,
.template-info {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx;
  background-color: #f8f9fa;
  border-radius: 12rpx;
  margin-top: 20rpx;
}

.area-name,
.role-name,
.template-name {
  font-size: 28rpx;
  color: #333;
}

.staff-count {
  font-size: 24rpx;
  color: #666;
  margin-left: 10rpx;
}

.selected-staff {
  display: flex;
  flex-wrap: wrap;
  gap: 10rpx;
  margin-top: 20rpx;
}

.staff-tag {
  display: flex;
  align-items: center;
  gap: 8rpx;
  padding: 8rpx 16rpx;
  background-color: #667eea;
  border-radius: 20rpx;
}

.staff-name {
  font-size: 24rpx;
  color: #fff;
}

.disabled-tip {
  margin-top: 10rpx;
  padding: 10rpx 20rpx;
  background-color: #f8f9fa;
  border-radius: 8rpx;
  border-left: 4rpx solid #ffc107;
}

.tip-text {
  font-size: 24rpx;
  color: #ffc107;
}

.shifts-list {
  margin-top: 20rpx;
}

.shift-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx;
  background-color: #f8f9fa;
  border-radius: 12rpx;
  margin-bottom: 20rpx;
}

.shift-info {
  flex: 1;
}

.shift-name {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
  display: block;
}

.shift-time {
  font-size: 24rpx;
  color: #666;
  display: block;
  margin-top: 8rpx;
}

.shift-actions {
  display: flex;
  gap: 10rpx;
}

.bottom-actions {
  display: flex;
  gap: 20rpx;
  padding: 30rpx;
  background-color: #fff;
  border-top: 1rpx solid #eee;
}

/* 弹窗遮罩样式 */
.popup-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  z-index: 9999;
  display: flex;
  align-items: center;
  justify-content: center;
  animation: fadeIn 0.3s ease-out;
}

@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}

.shift-edit-popup,
.preview-popup {
  width: 600rpx;
  max-width: 90vw;
  max-height: 80vh;
  background-color: #fff;
  border-radius: 20rpx;
  overflow: hidden;
  animation: slideUp 0.3s ease-out;
}

@keyframes slideUp {
  from { 
    transform: translateY(50px);
    opacity: 0;
  }
  to { 
    transform: translateY(0);
    opacity: 1;
  }
}

.popup-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx;
  border-bottom: 1rpx solid #eee;
}

.popup-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.popup-content {
  padding: 30rpx;
}

.popup-actions {
  display: flex;
  gap: 20rpx;
  padding: 30rpx;
  border-top: 1rpx solid #eee;
}

.preview-info {
  margin-bottom: 30rpx;
}

.preview-text {
  font-size: 26rpx;
  color: #666;
  display: block;
  margin-bottom: 10rpx;
}

.preview-schedule {
  margin-top: 20rpx;
}

.preview-title {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
  display: block;
  margin-bottom: 20rpx;
}

.schedule-preview-list {
  max-height: 400rpx;
  overflow-y: auto;
}

.preview-day {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 15rpx 20rpx;
  background-color: #f8f9fa;
  border-radius: 8rpx;
  margin-bottom: 10rpx;
}

.day-date {
  font-size: 24rpx;
  color: #333;
}

.day-shift {
  font-size: 24rpx;
  color: #666;
}
</style>
